import React, { Component } from 'react';
import sha1 from 'sha1';
import FilePanel from 'components/diffPanel';
import Diff from '../components/diff/diffWithComment';
import FileName from 'components/treeAndDiff/fileName';
import diffUtils from 'components/diff/utils.js';
import { Button, Tag, Checkbox, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import { getWebIdeUrl } from 'api';
import track from 'utils/track';
import LfsDeleteTag from 'components/lfs/deleteTag';
import LfsTag from 'components/lfs/lfsTag';
import utils from 'utils';
import { getFeature } from 'utils/features';
import './index.scss';
import intl from '../../../../../../../../../../locale';
import { getPathWithRootPath, navigateOpen } from 'utils/router';

const { pathResource, codeReviewDetail } = window.FORCE;

export default class Changes extends Component {
  state = {
    // 在弹窗中需要用到的埋点数据
    isPanelBodyShow: true,
  };

  togglePanelBody = () => {
    const { isPanelBodyShow } = this.state;
    this.setState({
      isPanelBodyShow: !isPanelBodyShow,
    });
  };

  goWebIde = (e, diff) => {
    e.preventDefault();
    getWebIdeUrl({
      filepath: diff.new_path,
      branch: codeReviewDetail.sourceBranch,
      commit: '',
      line: '',
      column: '',
      type: 'mergerequest',
      merge_commit: codeReviewDetail.targetBranch,
      mergerequestId: codeReviewDetail.id,
    })
      .then((result) => {
        navigateOpen(result.endpoint);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  toggleRead = (checked) => {
    const { diff, unreadFileObjectIds } = this.props;
    const read = !checked;
    track({
      action: read ? 'tag_read' : 'tag_unread',
      page: 'Repo-MR-changes',
      mr_id: codeReviewDetail.id,
    });

    const object_id = diff.deleted_file ? diff.old_object_id : diff.new_object_id;
    const index = unreadFileObjectIds.indexOf(object_id);
    if (read) {
      if (index > -1) {
        unreadFileObjectIds.splice(index, 1);
      }
      this.props.markFileAsRead(object_id, () => {
        this.props.updateData({
          unreadFileObjectIds,
        });
      });
    } else {
      if (index === -1) {
        unreadFileObjectIds.push(object_id);
      }
      this.props.markFileAsUnRead(object_id, () => {
        this.props.updateData({
          unreadFileObjectIds,
        });
      });
    }
  };

  renderWebIdeBtn = (diff) => {
    const { isArchive } = pathResource;
    const { rootCodeReviewDetail, ipSetting, project_clone_download } = this.props;

    if (!ipSetting) {
      return null;
    }

    if (ipSetting.ip_whitelist_enabled && ipSetting.scope === 'all') {
      return (
        <Balloon.Tooltip
          align="t"
          trigger={
            <Button type="normal" size="small" text style={{ marginLeft: 16 }} disabled>
              WebIDE
            </Button>
          }
        >
          {intl.get({
            id: 'code-assets.containers.file.fileItem.TheEnterpriseHasEnabledIp',
            defaultMessage: '企业已启用 IP 白名单严格管控，暂不支持使用 WebIDE',
          })}
        </Balloon.Tooltip>
      );
    } else if (
      project_clone_download?.httpCloneLimit?.state === 'disable' &&
      project_clone_download?.sshCloneLimit?.state === 'disable'
    ) {
      return (
        <Balloon.Tooltip
          align="t"
          trigger={
            <Button type="normal" size="small" text style={{ marginLeft: 16 }} disabled>
              WebIDE
            </Button>
          }
        >
          已启用仓库克隆下载控制，暂不支持使用 WebIDE，请联系管理员处理
        </Balloon.Tooltip>
      );
    }
    if (isArchive === 'false' && rootCodeReviewDetail.state !== 'merged') {
      return (
        <Button
          type="normal"
          size="small"
          text
          component="a"
          target="_blank"
          onClick={(e) => {
            track({
              action: 'goto_webide',
              page: 'Repo-MR-changes',
              mr_id: codeReviewDetail.id,
            });

            this.goWebIde(e, diff);
          }}
          style={{ marginLeft: 16 }}
        >
          WebIDE
        </Button>
      );
    }
    return null;
  };

  render() {
    const {
      diff,
      forceDiffViewType,
      commentsVisibleStatus,
      lastCommit,
      rootCodeReviewDetail,
      genWatermarkimage,
    } = this.props;
    const { isArchive, role } = pathResource;

    const diffsCount = diffUtils.getSingleDiffsCount(diff);
    const is_lfs = diff.is_new_lfs || diff.is_old_lfs;

    return (
      <div
        ref={(ref) => {
          this.filePanelRef = ref;
        }}
        style={{ marginBottom: 16 }}
        id={`file=${sha1(diff.deleted_file ? diff.old_path : diff.new_path)}`}
      >
        <div
          id={`${
            utils.isGenWatermarkimage(genWatermarkimage) ? 'diff_panel_waterMark_image' : null
          }`}
        >
          <FilePanel
            noBorderRadius
            id={`auchor_file_${sha1(diff.deleted_file ? diff.old_path : diff.new_path)}`}
            className={forceDiffViewType}
          >
            <FilePanel.Header>
              <div className="mr-detail-file-header">
                <div className={`mr-detail-file-header-left ${forceDiffViewType}`}>
                  <a className="text-black">
                    <FileName
                      item={{ ...diff, isHidden: !this.state.isPanelBodyShow }}
                      onChange={this.togglePanelBody}
                    />
                  </a>
                  {diffsCount ? (
                    <>
                      {diffsCount.additions ? (
                        <Balloon.Tooltip
                          trigger={<Tag color="green">+ {diffsCount.additions}</Tag>}
                          align="t"
                          text={`增加了 ${diffsCount.additions} 行`}
                        />
                      ) : null}
                      {diffsCount.deletions ? (
                        <Balloon.Tooltip
                          trigger={<Tag color="red">- {diffsCount.deletions}</Tag>}
                          align="t"
                          text={`删除了 ${diffsCount.deletions} 行`}
                        />
                      ) : null}
                    </>
                  ) : null}
                  {is_lfs && !diff.deleted_file && <LfsTag role={role} />}
                  {is_lfs && diff.deleted_file && <LfsDeleteTag />}
                </div>
                <div className="mr-detail-file-header-right">
                  <Checkbox checked={!diff.read} onChange={this.toggleRead}>
                    标记为未读
                  </Checkbox>
                  {/* 后面有内容时 */}
                  {(isArchive === 'false' && rootCodeReviewDetail.state !== 'merged') ||
                  (!diff.deleted_file && lastCommit.id) ? (
                    <span className="mr-detail-file-header-right-line" />
                  ) : null}
                  {/* 未归档且未合并通过 */}
                  {getFeature('WebIDE.entrance.mr') && this.renderWebIdeBtn(diff)}
                  {!diff.deleted_file && lastCommit.id ? (
                    <ButtonIcon
                      type="secondary"
                      component="a"
                      color="gray"
                      name="folder-line"
                      href={getPathWithRootPath(`/${pathResource.fullPath}/blob/${lastCommit.id}/${diff.new_path}`)}
                      target="_blank"
                      style={{ marginLeft: 16 }}
                      onClick={() => {
                        track({
                          action: 'view_src',
                          page: 'Repo-MR-changes',
                          mr_id: codeReviewDetail.id,
                        });
                      }}
                    />
                  ) : null}
                </div>
              </div>
            </FilePanel.Header>
            <FilePanel.Body noPadding>
              <div style={{ display: this.state.isPanelBodyShow ? 'block' : 'none' }}>
                <Diff
                  diff={diff}
                  viewType={forceDiffViewType}
                  commentsVisibleStatus={commentsVisibleStatus}
                  {...this.props}
                  ref={(ref) => {
                    this.diffRef = ref;
                  }}
                />
              </div>
            </FilePanel.Body>
          </FilePanel>
        </div>
      </div>
    );
  }
}
